package fu.ck;

import fu.ck.Util.MysqlUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

import java.util.Timer;
import java.util.TimerTask;

public class Main {

    public static int HTTP_PORT = 8443, MESSAGE_PORT = 8191;
    public static String MYSQL_URI = "120.25.216.222:3306/goods", MYSQL_USER = "root", MYSQL_PWD = "xxc65734101";

    public static void main(String[] args) throws Exception {
        new Main().start();
    }

    public void start() throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                NioEventLoopGroup group = new NioEventLoopGroup();
                try {
                    ServerBootstrap bootstrap = new ServerBootstrap();
                    bootstrap.group(group)
                            .channel(NioServerSocketChannel.class)
                            .localAddress(HTTP_PORT)
                            .childHandler(new ChannelInitializer<SocketChannel>() {
                                @Override
                                protected void initChannel(SocketChannel socketChannel) throws Exception {
                                    // server端发送的是httpResponse，所以要使用HttpResponseEncoder进行编码
                                    socketChannel.pipeline().addLast(new HttpResponseEncoder());
                                    // server端接收到的是httpRequest，所以要使用HttpRequestDecoder进行解码
                                    socketChannel.pipeline().addLast(new HttpRequestDecoder());
                                    socketChannel.pipeline().addLast(new HttpPostServerInboundHandler());
                                }
                            });
                    ChannelFuture f = bootstrap.bind().sync();
                    f.channel().closeFuture().sync();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        group.shutdownGracefully().sync();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                MysqlUtil.getInstance().heartBeat();
            }
        }, 10 * 60 * 1000, 10 * 60 * 1000);
    }
}
